<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>rand100</title>
    <style type="text/css">
    * {
        margin:0;
        padding:0;
    }
    #canvas {
        display: block;
        margin: 0 auto;
        border: 1px solid blue;
    }
    </style>
</head>
<body>
    <canvas id="canvas"></canvas>
</body>
</html>
<script type="text/javascript">
    var oCanvas = document.querySelector("canvas");
    var context = canvas.getContext("2d");
    oCanvas.width = 1600;
    oCanvas.height = 768;

    function rand(min, max) {
        return parseInt(Math.random() * (max - min)) + min;
    }

    function drawArc(xOrigin, yOrigin, r, sNum, eNum, color, lineWidth) {
        context.beginPath();
        context.fillStyle = color;
        context.lineWidth = lineWidth;
        context.arc(xOrigin, yOrigin, r, Math.PI / 180 * sNum, Math.PI / 180 * eNum);
        context.closePath();
        context.fill();
        
    }
    // 运动圆的参数定义
    var r = 30;
    var x = 30;
    var y =30;
    var speedX = 3;
    var speedY = 3;
    var color = `rgba(${rand(0,255)}, ${rand(0,255)}, ${rand(0,255)}, 1)`;

    // 随机生成目标圆
    var r1 = rand(100, 250);
    var x1 = rand(r1, oCanvas.width - r1);
    var y1 = rand(r1, oCanvas.height - r1);
    drawArc(x1, y1, r1, 0, 360, color, 0);

    function move() {
        // 检测是否碰到随机生成的圆        
        if (Math.pow((x - x1), 2) + Math.pow((y - y1), 2) < Math.pow((r + r1), 2)) {
            // 碰到目标圆，就将目标圆清空，重新生成一个随机的
            context.clearRect(x1 - r1, y1 - r1, 2 * r1, 2 * r1);
            r1 = rand(80, 300);
            x1 = rand(r1, oCanvas.width - r1);
            y1 = rand(r1, oCanvas.height - r1);
            drawArc(x1, y1, r1, 0, 360, color,0);
        }
        
        context.clearRect(x - r, y - r, 2 * r, 2 * r); //清除上一个圆的外切正方形区域
        context.clearRect(x-5,y+r,10,7);

        // 控制圆的移动
        x += speedX;
        y += speedY;
        if (x + r > oCanvas.width || x - r < 0) {
            speedX = -speedX;
        }
        if (y + r > oCanvas.height || y - r < 0) {
            speedY = -speedY;
        }
        
        drawArc(x, y, r,0, 360,"lightblue", 0);

        // 圆样式
        context.beginPath();
        context.strokeStyle = "white";
        context.lineWidth = 5;
        context.arc(x, y, r - 10, Math.PI / 180 * 290, Math.PI / 180 * 324);
        context.closePath();
        context.stroke();

        context.beginPath();
        context.fillStyle = "blue";
        context.fillRect(x-5,y+r,10,7);
        context.closePath();

        window.requestAnimationFrame(move);     
    }
    move();

</script>